package cn.javass.xgen.util.readxml;

import org.w3c.dom.Element;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 多个元素终结符
 */
public class ElementsTerminalExpression extends ReadXmlExpression {

    /**
     * 元素的名称
     */
    private String eleName = "";

    /**
     * 判断的条件
     */
    private String condition = "";

    public ElementsTerminalExpression(String eleName, String condition) {
        this.eleName = eleName;
        this.condition = condition;
    }

    @Override
    public String[] interpret(Context ctx) {
        //1.获取自己的多个元素
        //1.维护父级节点记录
        List<Element> pEles = ctx.getPreEles();
        List<Element> nowEles = new ArrayList<Element>();
        for (Element pEle : pEles) {
            nowEles.addAll(ctx.getNowEles(pEle, eleName));
        }
        //2.判断条件
        Iterator<Element> it = nowEles.iterator();
        while (it.hasNext()) {
            Element ele = it.next();
            if (!ctx.judgeCondition(ele, condition)) {
                it.remove();
            }
        }
        //3.获取元素值
        String[] ss = new String[nowEles.size()];
        for (int i = 0; i < ss.length; i++) {
            Element ele = nowEles.get(i);
            if (ele.getFirstChild() != null) {
                ss[i] = ele.getFirstChild().getNodeValue();
            } else {
                ss[i] = "";
            }
        }
        return ss;
    }
}
